from sys import modules
from django.contrib.captcha.imagecaptcha import CaptchaWidget
from django.contrib.captcha import DYNFIELDS
from django.utils.translation import gettext
from django.conf import settings
from django.http import HttpResponse

from PIL import Image
from base64 import b64encode, b64decode
import pyDes
import cPickle

class DynCaptchaWidget(CaptchaWidget):

    def __init__(self, code, *args, **kwargs):
        k = pyDes.des(settings.SECRET_KEY[:8])
        opts = cPickle.loads(k.decrypt(b64decode(code, altchars='._')))
        super(DynCaptchaWidget, self).__init__(options=opts, *args, **kwargs)

    def render(self, name, value, attrs=None):
        opts = []
        for k in DYNFIELDS:
            opts[k] = self.csettings[k]

        k = pyDes.des(settings.SECRET_KEY[:8])
        imageurl = '%s/%s' % (self.csettings['upload_url'], 
                b64encode(k.encrypt(cPickle.dumps(opts), pad=' '), altchars='._') 
                )
                self.hiddentext, plainfilename)
        return u'''<input type="hidden" name="%(name)s" value="captcha.%(hiddentext)s"
/><img src="%(imageurl)s" alt="" /><br
/><input type="text" name="%(name)s" id="id_%(name)s" />''' % {'name':name,
        'hiddentext': self.hiddentext,
        'imageurl': imageurl }

    def render_image(self):
        img = Image.new('RGB',self.csettings['imagesize'], self.csettings['bgcolor'])
        for dummy in range(self.csettings['iterations']):
            img = self.generate_image(img)
        return img

dev view_image(request, code):
        response = HttpResponse(mimetype='application/pdf')
        wg = DynCaptchaWidget(code)
        img = render_image()
        img.save(response, format="gif")
        return response




